import { messages } from "share/common";
import React, { Component } from 'react';
import { Button, Checkbox, Modal, Tooltip, message } from 'antd'
const ButtonGroup = Button.Group;
import 'styles/components/resize-table/resize-table-columns-setting.scss'
import resizeTableService from './resize-table.service'

class ColumnsSetting extends Component {

  state = {
    visible: false,
    columns: [],
    source: [],
    saving: false
  };

  componentDidMount() {
    const { tableName, onChangeColumnsLoading, onChange, columns } = this.props;
    if(tableName) {
      onChangeColumnsLoading(true);
      resizeTableService.getColumns(tableName)
        .then(res => {
          if(res.data.length > 0) {
            let source = this.getSourceByColumns(res.data, columns);
            this.setState({ source });
            onChange(this.handleColumns(source));
          }
        })
        .finally(() => {
          onChangeColumnsLoading(false);
        })
    }
  }

  //根据外部传入的columns更新source，主要是增删列的更新
  getSourceByColumns = (source, columns) => {
    //如果columns中没有source中有的列，则为删除对应列，设置deleted为true
    let target = source.map(s => {
      let item = columns.find(c => c.dataIndex === s.columnName);
      if(!item)
        s.deleted = true;
      return s;
    });
    let maxSequence = 0;
    columns.map(c => maxSequence = Math.max(maxSequence, c.sequence || 0));
    if(typeof maxSequence !== 'number')
      maxSequence = 0;
    //如果source中没有columns中有的列，则为增加对应列，增加到最后
    columns.map(c => {
      let item = source.find(s => s.columnName === c.dataIndex);
      if(!item)
        target.push({
          columnName: c.dataIndex,
          hide: false,
          width: (typeof c.width === 'number' && c.width) || 150,
          sequence: ++maxSequence,
          fixed: null
        });
    });
    return target;
  };

  handleColumns = source => {
    let result = [];
    const { columns } = this.props;
    let sortedData = source.sort((a, b) => a.sequence - b.sequence);
    sortedData.map(item => {
      let column = columns.find(c => c.dataIndex === item.columnName);
      if(column) {
        result.push({ ...column, hide: item.hide, width: item.width });
      }
    });
    return result;
  };

  onOk = () => {
    const { onChange } = this.props;
    const { columns } = this.state;
    const allColumns = this.props.columns;
    this.setState({ visible: false });
    onChange(allColumns.map((column, index) => {
      column.hide = columns[index].hide;
      return column;
    }));
  };

  onChangeColumn = (dataIndex, isShow) => {
    const { columns } = this.state;
    this.setState({ columns: columns.map(c => {
        c.dataIndex === dataIndex && (c.hide = !isShow);
        return c;
      })
    });
  };

  save = () => {
    const { tableName, columns } = this.props;
    const { source } = this.state;
    const result = [];
    columns.map((column, index) => {
      result.push({
        columnName: column.dataIndex,
        hide: column.hide || false,
        width: (typeof column.width === 'number' && column.width) || 150,
        sequence: index,
        fixed: null
      })
    });
    if(source.length > 0) {
      result.forEach(item => {
        let sourceItem = source.find(s => s.columnName === item.columnName);
        if(sourceItem)
          item.id = sourceItem.id;
        return item;
      })
    }
    this.setState({ saving: true });
    resizeTableService.saveColumns(tableName, result)
      .then(res => {
        this.setState({ source: res.data });
        message.success(messages('components.key1029')/*设置成功*/);
      })
      .finally(() => {
        this.setState({ saving: false });
      })
  };

  render() {
    const { columns, tableName } = this.props;
    const { visible, saving } = this.state;
    const stateColumns = this.state.columns;
    return (
      <ButtonGroup>
        <Modal
          className="resize-table-columns-setting"
          visible={visible}
          onOk={this.onOk}
          onCancel={this.toState({ visible: false })}
          title={messages('components.key946')/*自定义列*/}
        >
          <div className='resize-table-columns-setting-content'>
            {stateColumns.filter(c => c.dataIndex !== '_index').map(column => <Checkbox
              onChange={e => this.onChangeColumn(column.dataIndex, e.target.checked)}
              checked={!column.hide}
            >{column.title}</Checkbox>)}
          </div>
        </Modal>
        <Tooltip
          title={<span style={{ whiteSpace: 'nowrap' }}>{messages('components.key1041')/*列设置*/}</span>}
          placement='topLeft'
        >
          <Button
            icon='setting'
            onClick={this.toState({
              visible: true,
              columns: columns.map(column => ({
                hide: column.hide,
                dataIndex: column.dataIndex,
                title: column.title
              }))
            })}
          />
        </Tooltip>
        {tableName && (
          <Tooltip
            title={<span style={{ whiteSpace: 'nowrap' }}>
              {messages('components.key1042')/*保存列设置*/}
            </span>}
            placement='topLeft'
          >
            <Button icon={saving ? 'loading' : 'save'} onClick={this.save}/>
          </Tooltip>
        )}
      </ButtonGroup>
    );
  }
}

export default ColumnsSetting;
